// component/date-picker/date-picker.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    years: [],
    months: [],
    days: [],
    moment:['上午','下午'],
    currentMonth: 0,
    currentDay: 0,
    value: [0, 0, 0, 0],
    date: '',
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取日期的长度
     */
    getDateList(start, end) {
      let list = [];
      for (let i = start; i <= end; i++) {
        list.push(i)
      }
  
      return list;
    },
    /**
     * 获取日期
     */
    getDays(year, month, day = 0) {
      return new Date(year, month, day).getDate()
    },
    /**
     * 更改列选中
     */
    columnChange(e) {
      const { years, months, currentYear, currentMonth, currentDay, value: selValue } = this.data;
      const { value,column } = e.detail;
      if(column===0){
        const daysList = this.getDays(years[value], months[0], 0);
        let days = 0;
        let monthLength = 0;
        if (years[value] === currentYear) {
          monthLength= this.getDateList(currentMonth + 1, 12);
          days = this.getDateList(currentDay, daysList);
        } else {
          days = this.getDateList(1, daysList);
          monthLength = this.getDateList(1, 12);
        }
        this.setData({
          days,
          months: monthLength
        })
      }else if(column===1){
        const daysList = this.getDays(selValue[0], months[value], 0);
        let days = 0;
        if(months[value] === (currentMonth + 1)){
          days = this.getDateList(currentDay, daysList);
        }else{
          days = this.getDateList(1, daysList);
        }
        this.setData({
          days
        })
      }
    },
    /**
     * 确定选择的日期
     */
    handleComfirm(e) {
      this.setData({
        value: e.detail.value
      })
      const { years, months, days, value } = this.data;
      const time = value[3] ? '下午' : '上午';
      const month = (  months[value[1]] < 10 ? ( '0' + months[value[1]] ) : months[value[1]] );
      const day = ( days[value[2]] < 10 ? ( '0' +days[value[2]] ) : days[value[2]] );
      const date = `${years[value[0]]}-${month}-${day} ${time}`;
      this.triggerEvent('getSelectedDate', {date})
      this.setData({
        date
      })
    },
  },
  /**
   * 组件生命周期函数
   */
  lifetimes: {
    attached:function(){
      let date = new Date((new Date()/1000+86400)*1000);
      const currentYear = date.getFullYear();
      const currentMonth = date.getMonth();
      const currentDay = date.getDate();
      const years = this.getDateList(currentYear, currentYear+1);
      const months = this.getDateList(currentMonth + 1, 12);
      const monthsTotalDay = new Date(currentYear, currentMonth+1, 0).getDate();
      const days = this.getDateList(currentDay, monthsTotalDay);
      this.setData({
        years,
        months,
        days,
        currentYear,
        currentMonth,
        currentDay,
        value: [0, 0, 0]
      });
    },
  },
})
